package mytask.controller;

import javax.annotation.Resource;
import javax.validation.Valid;

import mytask.dao.UserDAO;
import mytask.domain.AuthManager;
import mytask.domain.TranslationManager;
import mytask.model.User;
import mytask.model.UserLogin;
import mytask.view.Screen;
import mytask.view.ScreenManager;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

@Controller
public final class LoginController extends MultiActionController {

	@Resource
	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logoutUser() {
		AuthManager.setPageUser(null);
		return "redirect:/";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView loginUser(@Valid @ModelAttribute("login") UserLogin userLogin, BindingResult result, Model model) {
		final ModelAndView screen = ScreenManager.get(Screen.HOME_GUEST);

		if (result.hasErrors()) {
			return screen;
		}

		final User user = userDAO.getUserByCredentials(userLogin.getEmail(), AuthManager.getSHA1(userLogin
				.getPassword()));
		if (user != null) {
			AuthManager.setPageUser(user);
			return (new ModelAndView(ScreenManager.REDIRECT_HOME));
		} else {
			screen.addObject("errors", TranslationManager.get("message.wrong-credentials"));
		}

		return screen;
	}

}